<?php

namespace app\api\controller\v12;

use app\api\controller\v2\Auth;
use app\common\cachemodel\CouponCode;
use app\common\cachemodel\CouponUseRange;
use app\common\cachemodel\UserCoupon;
use app\common\cachemodel\UserCouponGiveRecord;
use app\common\cachemodel\ZhunleActivity;
use app\common\cachemodel\ZlCouponActive;
use app\common\lib\Util;
use think\response\Json;

class Coupon extends Auth
{
    /**
     * 卡卷中心
     * @return Json
     * @throws \Exception
     */
    public function index()
    {
        $type = input('type/d', 1);

        $userCoupon = new UserCoupon();

        $data = $userCoupon->getList($this->user['id'], $type);

        $data['data'] = $userCoupon->dataFormatting($data['data']);

        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 卡卷搜索
     * @return Json
     */
    public function codeSearch()
    {
        $code = input('code/s', '');

        if (empty($code)) return show(config('code.error'), '请输入兑换码！');

        $cData = (new CouponCode())->search($code);

        if (empty($cData)) return show(config('code.error'), '您输入的兑换码无效！');

        switch ($cData['use_status'])
        {
            case 2:
                return show(config('code.error'), '您输入的兑换码已过期！');
                break;
            case 1:
                return show(config('code.error'), '您输入的兑换码已被领取！');
                break;
            case 0:
                $urData = (new CouponUseRange())->getInfoByIds($cData['ur_id']);

                if ($cData['expire_type'] == 1)
                {   // 固定到期时间
                    if ($cData['expire_time'] !== 0)
                    {
                        $timeDes = '有效期至' . date('Y.m.d', $cData['expire_time']);
                    } else
                    {
                        $timeDes = '';
                    }
                } else
                {   // 固定过期天数
                    if ($cData['expire_day'] !== 0)
                    {
                        $timeDes = '有效期至' . date('Y.m.d', strtotime("+{$cData['expire_day']} day"));
                    } else
                    {
                        $timeDes = '';
                    }
                }

                $isGiveTxt = [
                    0 => '、本券不可赠与好友使用。',
                    1 => '、本券可赠与好友使用，优惠条件以及有效期不变。',
                ];

                $isGive = $cData['is_give'] ?? 0;
                $urInfo = array_filter($urData[$cData['ur_id']] ?? []);
                $urInfo[] = (count($urInfo) + 1) . $isGiveTxt[$isGive];

                $cInfo = [
                    'name' => $cData['name'],
                    'desc' => $cData['desc'],
                    'time_des' => $timeDes,
                    'dtype' => (int)$cData['type'],
                    'discount' => $cData['discount'] ?? '',
                    'condition' => (int)($cData['condition'] ?? 0),
                    'use_rule' => $urInfo,
                ];

                return show(config('code.success'), '请求成功', $cInfo);
                break;
            default:
                return show(config('code.error'), '您输入的兑换码无效！');
        }
    }

    /**
     * 优惠券领取
     * @return Json
     * @throws \Exception
     */
    public function codeGet()
    {
        $code = input('code/s', '');

        if (empty($code)) return show(config('code.error'), '兑换码不存在！');

        $couponCodeModel = new CouponCode();
        $res = $couponCodeModel->codeGet($this->user['id'], $code);

        if ($res)
        {
            return show(config('code.success'), '领取成功；已存放至“我的-卡券中心”。');
        } else
        {
            return show(config('code.error'), $couponCodeModel->errorMsg);
        }
    }

    /**
     * 下单获取可用优惠券
     * @return Json
     * @throws \Exception
     */
    public function getOrderUsable()
    {
        $gids = input('gids/s', '');
        $price = input('price/s', '');

        $gidsArr = explode(',', $gids);

        $userCoupon = new UserCoupon();

        $couponList = $userCoupon->getUsableList((int)$this->user['id'], $gidsArr, $price);

        $data = $userCoupon->dataFormatting($couponList);

        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 下单获取可用优惠券数量
     * @return Json
     * @throws \Exception
     */
    public function getUsableNum()
    {
        $gids = input('gids/s', '');
        $goods_type = input('goods_type/d', 0);
        $start_time = input('start_time/s', '');
        $rid = input('rid/d', 0);
        $rid2 = input('rid2/d', 0);

        if ($rid)
        {
            $recode = (new \app\common\model\Recode())->getRecode(['id' => $rid]);
            if (!$recode)
            {
                return show(config('code.error'), '档案不存在');
            }
        }

        $userCoupon = new UserCoupon();
        $ActiveModel = new ZhunleActivity();
        $GoodsModel = new \app\common\cachemodel\Goods();

        //数据初始化
        $arr = [
            'num' => 0,
            'active_data' => null
        ];
        $gidsArr = explode(',', $gids);
        $gid = current($gidsArr);
        //检测当前用户是否时vip
        $is_vip = Util::getVips($this->user['id'], $goods_type, $rid,$gid);
        //内部vip不参与活动和优惠券
        if (!$is_vip)
        {
            $goods = $GoodsModel->batchGetInfoByIds($gidsArr);
            if ($goods)
            {
                //幸运之城折扣针对gtype
                $map_price = 0;
                $discount = null;
                $active_name = '';
                if ($goods_type == 5)
                {
                    $activing = $ActiveModel->getActivingGood($goods_type, 0);
                    foreach ($goods as $good)
                    {
                        $map_price += $good['now_prize'];
                    }
                    if ($activing)
                    {
                        $price = $map_price * $activing['attr'];
                        $active_name = $activing['name'];
                        $discount = $activing['attr'];
                    } else
                    {
                        $price = $map_price;
                    }
                } else//其他商品针对gid
                {
                    $goods = $goods ? current($goods) : [];
                    $price = $goods['now_prize'];
                    $activing = $ActiveModel->getActivingGood($goods_type, $goods['id'], $start_time);
                    if ($activing)
                    {
                        $actiGids = explode(',', $activing['gids']);
                        if (!array_diff($gidsArr, $actiGids))
                        {
                            //                    if ($gidsArr == explode(',', $activing['gids']))
                            if (in_array($gid, explode(',', $activing['gids'])))
                            {
                                $price = $goods['now_prize'] * $activing['attr'];
                                $active_name = $activing['name'];
                                $discount = $activing['attr'];
                            }
                        }
                    }
                }
                //获取当前商品的折后价
                $couponList = $userCoupon->getUsableList((int)$this->user['id'], $gidsArr, $price);
                $arr['num'] = count($couponList);
                if (isset($discount))
                {
                    $arr['active_data'] = [
                        'name' => $active_name,
                        'discount' => $discount
                    ];
                }
            }
        }

        if ($goods_type === 17 && $start_time)
        {
            $synastryReportGoods = (new \app\common\cachemodel\Goods())->GoodsTypeInfo(17);
            foreach ($synastryReportGoods as $key => $item)
            {
                if (!isset($item['good_list'][$gid]))
                {
                    continue;
                }
                $srid = $key;
                $relationId = $item['good_list'][$gid]['relation_id'];
                $sTime = strtotime($start_time . '-01');
                $start_time = (int)date('Ym', $sTime);
                $endTime = (int)date('Ym', strtotime($item['good_list'][$gid]['expire_time'], $sTime));

                $arr['notice'] = $GoodsModel->getSynastryReportUnlockNotice($this->user['id'], $rid, $rid2, $srid, $relationId, $start_time, $endTime);
                break;
            }
        } else
        {
            $arr['notice'] = $GoodsModel->getFortuneUnlockInfo($goods_type, $this->user['id'], $rid, $gid, $start_time);
        }
        return show(config('code.success'), '请求成功', $arr);
    }

    /**
     * 优惠券赠送
     * @return Json
     * @throws \Exception
     */
    public function couponGive()
    {
        $uen = input('uen/s', '');
        $cId = input('cid/d', 0);

        if (empty($uen) || empty($cId)) return show(config('code.error'), '服务异常');

        $uInfo2 = (new \app\common\cachemodel\User())->uenSearch((int)$this->user['id'], $uen, 'id,nickname');

        if (empty($uInfo2)) return show(config('code.error'), '被赠送用户不存在！');

        $userCoupon = new UserCoupon();

        $res = $userCoupon->couponGive((int)$this->user['id'], (int)$uInfo2['id'], $cId, $this->user);

        if ($res)
        {
            return show(config('code.success'), "恭喜您成功将优惠券赠与\n{$uInfo2['nickname']}");
        } else
        {
            return show(config('code.error'), $userCoupon->errorMsg);
        }
    }

    /**
     * 优惠券赠送记录列表
     * @return Json
     * @throws \Exception
     */
    public function giveRecordList()
    {
        $data = (new UserCouponGiveRecord())->getRecordList((int)$this->user['id']);

        return show(config('code.success'), "请求成功", $data);
    }

    /**
     * 优惠券赠送记录详情
     * @return Json
     * @throws \Exception
     */
    public function giveRecordDetail()
    {
        $cId = input('cid/d', 0);

        $data = (new UserCouponGiveRecord())->getRecordDetail((int)$this->user['id'], $cId);

        return show(config('code.success'), "请求成功", $data);
    }

    /**
     * 领取用户可领取优惠券
     * @return Json
     * @throws \think\exception\PDOException
     */
    public function activeGetCoupon()
    {
        $couponActiveModel = new ZlCouponActive();

        $res = $couponActiveModel->couponGive((int)$this->user['id']);

        if ($res)
        {
            return show(config('code.success'), '已存放至"我的-卡券中心"');
        } else
        {
            return show(config('code.error'), $couponActiveModel->errorMsg);
        }
    }
}
